﻿using System;
using System.Collections.Generic;
using System.Linq;
using IQToolkit;
using IQToolkit.Data;
using Infrastucture.Factories;
using TimeSplicerModule.DataModels;
using TimeSplicerModule.DomainModels;

namespace TimeSplicerModule.Factories
{
    public interface IProjectUserFactory : Infrastucture.Factories.IFactory<ProjectUserDataModel, ProjectUserModel>
    {
        List<ProjectUserModel> GetList(List<UserModel> users, List<ProjectRoleModel> projectRoles);
    }

    public class ProjectUserFactory : Factory<ProjectUserDataModel, ProjectUserModel>, IProjectUserFactory
    {
        public ProjectUserFactory(DbEntityProvider provider, IEntityTable<ProjectUserDataModel> db)
            : base(provider, db)
        {

        }

        public override ProjectUserModel Add(ProjectUserModel obj)
        {
            // need to make sure that user does not already belong to project
            var exsiting = Get(x => x.ProjectGuid == obj.ProjectGuid
                && x.UserGuid == obj.UserGuid);

            if (exsiting == null)
                return base.Add(obj);
            else 
            {
                obj.ProjectUserGuid = exsiting.ProjectUserGuid;
                return base.Save(obj);
            }
        }

        public List<ProjectUserModel> GetList(List<UserModel> users, List<ProjectRoleModel> projectRoles)
        {
            var models = GetList();

            foreach (var m in models)
            {
                m.ProjectRole = projectRoles.FirstOrDefault(x => x.ProjectRoleGuid == m.ProjectRoleGuid);
                m.User = users.FirstOrDefault(x => x.UserGuid == m.UserGuid);
            }

            return models;
        }
    }
}
